#include "loginwindow.h"

LoginWindow::LoginWindow(QWidget *parent)
    : QWidget(parent)
{
    resize(400, 300);
    showCentered();

    QLabel *usernameLabel = new QLabel("用户名:", this);
    QLabel *passwordLabel = new QLabel("密  码:", this);

    _usernameLineEdit = new QLineEdit(this);
    _passwordLineEdit = new QLineEdit(this);
    _passwordLineEdit->setEchoMode(QLineEdit::Password);

    QPushButton *loginButton = new QPushButton("登录", this);
    QPushButton *registButton = new QPushButton("注册", this);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    QHBoxLayout *usernameLayout = new QHBoxLayout;
    QHBoxLayout *passwordLayout = new QHBoxLayout;

    usernameLayout->addWidget(usernameLabel);
    usernameLayout->addWidget(_usernameLineEdit);
    passwordLayout->addWidget(passwordLabel);
    passwordLayout->addWidget(_passwordLineEdit);

    mainLayout->addLayout(usernameLayout);
    mainLayout->addLayout(passwordLayout);
    mainLayout->addWidget(loginButton);
    mainLayout->addWidget(registButton);

    setLayout(mainLayout);

    connect(loginButton, &QPushButton::clicked, this, &LoginWindow::onLoginButtonClicked);
    connect(registButton, &QPushButton::clicked, this, &LoginWindow::onRegistButtonClicked);
}

void LoginWindow::showCentered()
{
    if (parentWidget()) {
        QRect parentGeometry = parentWidget()->geometry();
        int x = parentGeometry.x() + (parentGeometry.width() - this->width()) / 2;
        int y = parentGeometry.y() + (parentGeometry.height() - this->height()) / 2;
        this->move(x, y);
    }
}

void LoginWindow::onLoginButtonClicked()
{
    QString username = _usernameLineEdit->text();
    QString password = _passwordLineEdit->text();
    QString realPassword = SqlHelper::instance().getPassword(username);
    if (username == "" || password == "")
    {
        MessageBox("登陆失败", this).exec();
    }
    if (password == realPassword)
    {
        MessageBox("登陆成功", this).exec();

        User::instance().setUser(username);

        // 多态
        QWidget * window = nullptr;

        QString type = SqlHelper::instance().getType(username);
        if (type == "user") {
            window = new CheckinWindow();
        } else if (type == "admin") {
            window = new AdminWindow();
        } else {
            qDebug() << "Wrong user type, please check code!";
            assert(false);
        }

        if (window) window->show();
    }
    else {
        MessageBox("登陆失败", this).exec();
    }
}

void LoginWindow::onRegistButtonClicked()
{
    QString username = _usernameLineEdit->text();
    QString password = _passwordLineEdit->text();


    if (SqlHelper::instance().insertUser(username, password, "user"))
        MessageBox("注册成功", this).exec();
    else
        MessageBox("注册失败", this).exec();
}
